package com.itheima.reggie.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    //登录功能
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //接收前端参数
        String username = map.get("username");
        String password = map.get("password");
        //调用service
        ResultInfo resultInfo = employeeService.login(username, password);
        //将查回来的数据库中已经有的用户放入session,不用重复登录
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);
        //最终返回
        return resultInfo;
    }
    //退出登录功能
    @PostMapping("employee/logout")
    public ResultInfo loginOut(){
        //清除session
        session.invalidate();
        //返回成功标识
        return ResultInfo.success(null);
    }

    //查询后台管理员列表
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name){
        List<Employee> employeeList = employeeService.findByName(name);
        return ResultInfo.success(employeeList);
    }

    //添加员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
      /*  //补全参数
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        employee.setPassword(SecureUtil.md5("123"));
        employee.setStatus(Employee.STATUS_ENABLE);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
        //调用service
        employeeService.save(employee);
        return ResultInfo.success(null);
    }

    //根据id查询
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    //修改员工信息
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }



}
